<template>
  <div class="Echarts">
    <div ref="chartDom" style="width: 100%;height: 100%"></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, reactive, watch } from 'vue';
import { getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const chartDom = ref(null);
let myChart = null;
const chartData = reactive([]); // Using reactive to create a reactive array

onMounted(() => {
  if (chartDom.value) {
    myChart = echarts.init(chartDom.value);

    const option = {
      tooltip: {
        trigger: 'axis',
        position: (pt) => [pt[0], '10%'],
      },
      toolbox: {
        feature: {
          dataZoom: { yAxisIndex: 'none' },
          restore: {},
          saveAsImage: {},
        },
      },
      xAxis: {
        type: 'time',
        boundaryGap: false,
        axisLabel: {
          formatter: (value) => {
            const date = new Date(value);
            const seconds = date.getSeconds().toString().padStart(2, '0');
            return `${seconds}`; // Display hours, minutes, seconds, and milliseconds
          },
        },
        splitLine: {
          show: true,
          interval: 0, // Show all grid lines
        },
      },
      yAxis: {
        type: 'value',
      },
      dataZoom: [
        {
          type: 'inside',
        },
        {
          show: true,
          type: 'slider',
        },
      ],
      series: [
        {
          name: 'Next 24 Hours Data',
          type: 'line',
          smooth: true,
          symbol: 'none',
          areaStyle: {},
          data: chartData, // Using reactive array
        },
      ],
    };

    myChart.setOption(option);

    // Listen for SignalR messages
    if (proxy.signalr && proxy.signalr.SR) {
      let updateTimeout = null;

      proxy.signalr.SR.on("", (value) => {
        const now = new Date().getTime();
        chartData.push([now, value]);

        if (updateTimeout) {
          clearTimeout(updateTimeout);
        }

        updateTimeout = setTimeout(() => {
          myChart.setOption({
            series: [{
              data: chartData,
            }],
          });
          // Keep only the last 24 hours of data
          while (chartData.length > 0 && (now - chartData[0][0]) > 86400000) { // Adjusted for 24 hours in milliseconds
            chartData.shift();
          }
        }, 100); // Update every 100ms
      });
    } else {
      console.error('SignalR connection is not initialized.');
    }
  }
});

// Limit chartData length to the last 100 entries
watch(chartData, (newValue) => {
  if (newValue.length > 100) {
    newValue.shift();
  }
});
</script>

<style scoped>
.Echarts {
  width: 100%;
  height: 400px;
}
</style>
